﻿using Fleck;

namespace FleckDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            WebSockSvr server = new WebSockSvr();
            server.Start();

            server.SendDatas();
            Console.ReadLine();
        }
    }

    public class WebSockSvr
    {
        public List<IWebSocketConnection> ClinetList = new();
        private WebSocketServer service;

        public WebSockSvr() 
        {
            service = new WebSocketServer("ws://0.0.0.0:8181");
        }

        public void Start() 
        {
            service.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console.WriteLine("Open!");
                    ClinetList.Add(socket);
                };
                socket.OnClose = () =>
                {
                    Console.WriteLine("Close!");
                    ClinetList.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    ClinetList.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });
        }

        public void SendDatas()
        {
            for (int i = 0; i < 200; i++)
            {
                Task.Run(async () =>
                {
                    while (true)
                    {
                        try
                        {
                            for (int j = 0; j < ClinetList.Count; j++)
                            //foreach (var sock in allSockets)
                            {
                                var sock = ClinetList[j];
                                if (sock.IsAvailable)
                                {
                                    await sock.Send($"Dev[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}, 12.34, 34.56, 56.78, \"77705683\"]");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("出现异常：" + ex.Message + "\r\n" + ex.StackTrace);
                        }
                        finally
                        {
                            await Task.Delay(1000);
                        }
                    }
                });
            }
        }
    }
}
